<template>
  <div class="favorites-page" :class="{ 'slide-in': isVisible }">
    <div class="header">
      <van-icon name="arrow-left" class="back-icon" @click="handleBack" />
      <span class="title">我的收藏</span>
      <div v-if="favoritesList.length > 0" class="clear-btn" @click="handleClear">
        <van-icon name="delete-o" />
      </div>
    </div>

    <div class="content">
      <div v-if="favoritesList.length === 0" class="empty-state">
        <van-empty description="暂无收藏内容" />
      </div>

      <div v-else class="favorites-list">
        <div v-for="item in favoritesList" :key="item.id" class="favorite-item" @click="handleItemClick(item)">
          <div class="thumbnail-container">
            <img :src="item.cover || getDefaultCover()" :alt="item.title" class="thumbnail" />
            <div v-if="item.duration" class="duration-badge">
              {{ formatDuration(item.duration) }}
            </div>
            <div class="play-icon">
              <van-icon name="play-circle-o" color="#fff" size="30" />
            </div>
          </div>

          <div class="info">
            <div class="title">{{ item.title }}</div>
            <div class="author">UP {{ item.author.name }}</div>
            <div class="timestamp">{{ formatTime(item.favoritedAt) }}</div>
          </div>

          <div class="delete-btn" @click.stop="handleDelete(item.id)">
            <van-icon name="cross" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useFavoritesStore, type FavoriteItem } from '@/stores/favorites'
import { useVideoStore } from '@/stores/counter'
import { showConfirmDialog, showToast } from 'vant'

const router = useRouter()
const favoritesStore = useFavoritesStore()
const videoStore = useVideoStore()

// 动画状态
const isVisible = ref(false)

// 计算属性
const favoritesList = computed(() => favoritesStore.favoritesList)

// 格式化时长
const formatDuration = (seconds: number): string => {
  if (!seconds) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

// 格式化时间
const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const targetDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())

  if (targetDate.getTime() === today.getTime()) {
    // 今天
    const hours = date.getHours()
    const minutes = date.getMinutes()
    return `今天 ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
  } else {
    // 其他日期
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hours = date.getHours()
    const minutes = date.getMinutes()
    return `${year}年${month}月${day}日 ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
  }
}

// 获取默认封面
const getDefaultCover = (): string => {
  return ''
}

// 处理返回
const handleBack = () => {
  // 触发退出动画
  isVisible.value = false
  // 等待动画完成后再路由返回
  setTimeout(() => {
    router.back()
  }, 300)
}

// 处理点击视频项
const handleItemClick = (item: FavoriteItem) => {
  // 设置当前视频并跳转
  videoStore.setCurrentVideo({
    id: item.id,
    title: item.title,
    description: item.description,
    playUrl: item.playUrl,
    cover: item.cover,
    author: item.author,
    duration: item.duration,
    tags: item.tags,
    consumption: item.consumption
  })

  router.push(`/video/${item.id}`)
}

// 处理删除单个收藏
const handleDelete = (videoId: string | number) => {
  showConfirmDialog({
    title: '确认删除',
    message: '确定要取消收藏这个视频吗？',
    confirmButtonText: '删除',
    cancelButtonText: '取消'
  })
    .then(() => {
      if (favoritesStore.removeFavorite(videoId)) {
        showToast('已取消收藏')
      }
    })
    .catch(() => {
      // 用户取消
    })
}

// 处理清空收藏
const handleClear = () => {
  if (favoritesList.value.length === 0) return

  showConfirmDialog({
    title: '确认清空',
    message: '确定要清空所有收藏吗？',
    confirmButtonText: '清空',
    cancelButtonText: '取消'
  })
    .then(() => {
      favoritesStore.clearFavorites()
      showToast('已清空收藏')
    })
    .catch(() => {
      // 用户取消
    })
}

// 处理登录成功
const handleLoginSuccess = () => {
  favoritesStore.loadFavorites()
}

// 触发进入动画
const triggerEnterAnimation = () => {
  // 确保初始状态是隐藏的（translateX(100%)）
  isVisible.value = false

  // 延迟一帧确保DOM已渲染，然后触发进入动画
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      isVisible.value = true
    })
  })
}

// 组件挂载时初始化
onMounted(() => {
  // 重新加载收藏数据
  favoritesStore.loadFavorites()

  // 监听登录成功事件
  window.addEventListener('loginSuccess', handleLoginSuccess)

  // 触发进入动画
  triggerEnterAnimation()
})

// 组件激活时触发动画（处理 keep-alive 情况）
onActivated(() => {
  // 重新加载收藏数据
  favoritesStore.loadFavorites()

  // 触发进入动画
  triggerEnterAnimation()
})

onUnmounted(() => {
  isVisible.value = false
  // 移除登录成功事件监听
  window.removeEventListener('loginSuccess', handleLoginSuccess)
})
</script>

<style scoped lang="less">
.favorites-page {
  width: 100vw;
  min-height: 100vh;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  transform: translateX(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.slide-in {
    transform: translateX(0);
  }

  .header {
    width: 100%;
    height: 6vh;
    padding: 0 4vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    gap: 3vw;
    border-bottom: 1px solid #f5f5f5;
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 10;

    .back-icon {
      font-size: 18px;
      color: #333;
      cursor: pointer;
    }

    .title {
      flex: 1;
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .clear-btn {
      font-size: 18px;
      color: #666;
      cursor: pointer;
      padding: 4px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:active {
        opacity: 0.6;
      }
    }
  }

  .content {
    width: 100%;
    padding: 2vh 4vw;
    box-sizing: border-box;
    padding-bottom: 10vh;

    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 60vh;
    }

    .favorites-list {
      display: flex;
      flex-direction: column;
      gap: 3vh;

      .favorite-item {
        display: flex;
        gap: 3vw;
        cursor: pointer;
        transition: background-color 0.2s;
        padding: 1vh 0;
        border-radius: 8px;
        position: relative;

        &:active {
          background-color: #f9f9f9;
        }

        .thumbnail-container {
          position: relative;
          width: 35vw;
          aspect-ratio: 16 / 9;
          border-radius: 8px;
          overflow: hidden;
          flex-shrink: 0;
          background-color: #f5f5f5;

          .thumbnail {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .duration-badge {
            position: absolute;
            bottom: 4px;
            right: 4px;
            background-color: rgba(0, 0, 0, 0.6);
            color: #fff;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 4px;
            z-index: 2;
          }

          .play-icon {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1;
          }
        }

        .info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          min-width: 0;
          padding: 0.5vh 0;

          .title {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 1vh;
          }

          .author {
            font-size: 12px;
            color: #999;
            margin-bottom: 0.5vh;
          }

          .timestamp {
            font-size: 11px;
            color: #999;
          }
        }

        .delete-btn {
          position: absolute;
          top: 1vh;
          right: 0;
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          color: #fff;
          font-size: 14px;
          cursor: pointer;
          z-index: 10;

          &:active {
            background-color: rgba(0, 0, 0, 0.7);
          }
        }
      }
    }
  }
}
</style>
